Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

Solution:

  1. public class Solution {
  2. public int maxProduct(int[] nums) {
  3. int n = nums.length;
  4. int res = nums[0];
  5. int min = nums[0];
  6. int max = nums[0];
  7. for (int i = 1; i < n; i++) {
  8. if (nums[i] > 0) {
  9. max = Math.max(nums[i], max * nums[i]);
  10. min = Math.min(nums[i], min * nums[i]);
  11. } else {
  12. int tmp = max;
  13. max = Math.max(nums[i], min * nums[i]);
  14. min = Math.min(nums[i], tmp * nums[i]);
  15. }
  16. res = Math.max(res, max);
  17. }
  18. return res;
  19. }
  20. }